package cn.org.xwb.bookmall.model.service.impl;

import cn.org.xwb.bookmall.model.po.Car;
import cn.org.xwb.bookmall.model.mapper.CarMapper;
import cn.org.xwb.bookmall.model.service.ICarService;
import cn.org.xwb.bookmall.model.utils.BookRedisUtil;
import cn.org.xwb.bookmall.model.vo.CarVo;
import cn.org.xwb.common.redis.utils.RedisUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author xwb
 * @since 2023-12-05
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BookRedisUtil bookRedisUtil;

    private String getKeyCars(Long id) {
        return bookRedisUtil.getRedisKeyUser("car:%s", String.valueOf(id));
    }

    @Override
    public List<CarVo> findAndCacheAll(Long id) {
        // 查询
        List<CarVo> carVos = baseMapper.selectAllCarByUserId(id);
        Boolean res = redisUtil.setList(getKeyCars(id), carVos);
        if (!res) return null;
        return carVos;
    }

    @Override
    public List<CarVo> findAllFromCache(Long id) {
        List<CarVo> carVos = (List<CarVo>) redisUtil.get(getKeyCars(id));
        if (Objects.isNull(carVos)) carVos = findAndCacheAll(id);
        if (Objects.isNull(carVos)) return null;
        return carVos;
    }

    
}
